import dgram from 'react-native-udp';

export default class SocketUtil {
    constructor() {
        this.socket = undefined;
        this.socketReady = false;
    }

    close() {
        if(this.socket != undefined) {
            this.socket.close();
            this.socketReady = false;
        }
    }
    initSocket(onMessage, readyCallback) {
        this.close();

        this.socket = dgram.createSocket('udp4');
        if(this.socket == undefined) {
            return;
        }
        this.socket.bind(0);
        this.socket.once('listening', () => {
            this.socket.setBroadcast(true);
            this.socketReady = true;
            if(readyCallback != undefined) {
                readyCallback();
            }
        });

        this.socket.on('message', onMessage);
    }

    send(ipaddr, port, data) {
        if(!this.socketReady) {
            console.error("socket not ready.");
            return;
        }

        this.socket.send(data, 0, data.length, port, ipaddr, (err) => {
            if (err) {
                console.error('Send message error: ' + error);
            }
        });
    }
}
